package com.gec.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gec.aspect.RequestContext;
import com.gec.config.WebSocketConfig;
import com.gec.exception.BusinessException;
import com.gec.exception.BusinessExceptionCode;
import com.gec.javabean.Doc;
import com.gec.mapper.DocMapper;
import com.gec.service.DocService;
import com.gec.service.WsService;
import com.gec.utils.RedisUtil;
import com.gec.websocket.WebSocketServer;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

@Service
public class DocServiceImpl extends ServiceImpl<DocMapper, Doc> implements DocService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private WsService wsService;

    @Override
    public int increaseViewCount(int id) {
        return this.baseMapper.increaseViewCount(id);
    }
    @Override
    public int increaseVoteCount(int id) {
//        远程IP+doc.id作为key，24小时内不能重复
        String ip = RequestContext.getRemoteAddr();

//        推送消息
        Doc docDB = this.baseMapper.selectById(id);
        String logId = MDC.get("LOG_ID");
        if (redisUtil.validateRepeat("DOC_VOTE_" + id + "_" + ip, 3600 * 24)) {
            wsService.sendInfo("【" + docDB.getName() + "】" + "被点赞了！",logId);
            return this.baseMapper.increaseVoteCount(id);
        } else {
            wsService.sendInfo("【" + docDB.getName() + "】" + "这篇文章您已经点过赞了！",logId);
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }

    }

    @Override
    public int updateEbookInfo() {
        return this.baseMapper.updateEbookInfo();
    }
}